package com.lqwu.mallchatserver.user.controller;

import com.lqwu.mallchatserver.user.service.WxMsgService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("wx/portal/public")
@Api(value = "微信相关模块接口")
public class WxPortalController {

    private final WxMpService wxService;
    private final WxMpMessageRouter messageRouter;
    private final WxMsgService wxMsgService;


    /**
     * 微信公众号URL接入 （用于测试）
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    /**
     * 微信OAuth2授权回调处理逻辑
     * @param code
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/callback")
    public RedirectView callback(@RequestParam String code) throws WxErrorException {
        // 获取用户信息
        WxOAuth2AccessToken token = wxService.getOAuth2Service().getAccessToken(code);
        WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(token, "zh_cn");
        log.info("用户信息:{}", userInfo);
        // 调用授权
        wxMsgService.authorize(userInfo);
        return new RedirectView("www.mallchat.cn");
    }
}